package wlt.plan.view;

import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import wlt.plan.controller.Search;
import wlt.plan.controller.TodoManager;
import wlt.plan.model.TodoItem;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class TodoApp {
    private ListView<TodoItem> todoListView;                        // 任务列表视图
    private TextField inputField;                                   // 输入新任务的文本框
    private LocalDate currentDate;                                  // 当前选中的日期
    private Label dateLabel;                                        // 显示当前日期
    private final TodoManager manager;                              // 任务管理器
    private final DateTimeFormatter dateFormatter =
        DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE");          // 日期格式化器
    private final Search searchController;                          // 搜索控制器
    private final ComboBox<TodoItem.Priority> priorityComboBox;     // 添加优先级选择下拉框
    
    // 初始化搜索控制器
    public TodoApp(TodoManager manager) {
        this.manager = manager;
        this.currentDate = LocalDate.now();
        this.searchController = new Search(); // 直接初始化 Search（使用其内部创建的 TextField）
        
        // 初始化优先级选择下拉框
        this.priorityComboBox = new ComboBox<>();
        this.priorityComboBox.getItems().addAll(TodoItem.Priority.values());
        this.priorityComboBox.setValue(TodoItem.Priority.MEDIUM); // 默认选择中等重要
        // 设置显示文本转换器
        this.priorityComboBox.setCellFactory(param -> new ListCell<>() {
            @Override
            protected void updateItem(TodoItem.Priority item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    switch (item) {
                        case HIGH:
                            setText("重要"); break;
                        case MEDIUM:
                            setText("中等"); break;
                        case LOW:
                            setText("次要"); break;
                    }
                }
            }
        });
        this.priorityComboBox.setButtonCell(new ListCell<>() {
            @Override
            protected void updateItem(TodoItem.Priority item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    switch (item) {
                        case HIGH:
                            setText("重要"); break;
                        case MEDIUM:
                            setText("中等"); break;
                        case LOW:
                            setText("次要"); break;
                    }
                }
            }
        });
    }
    
    // 窗口布局
    public Scene createScene() {
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.setStyle("-fx-background-color: #f0f0f0;");
        
        // 集成背景图片
        BackPhoto.setBackgroundImage(root);
        
        // 顶部区域：日期+搜索框
        // 用 VBox 垂直排列日期控件和搜索框
        VBox topContainer = new VBox(10);
        topContainer.setPadding(new Insets(5));
        
        // 日期选择区域
        HBox dateControlBox = createDateControlBox();
        // 搜索区域（使用 Search 控制器内部的 TextField）
        HBox searchBox = createSearchBox();
        
        // 将日期控件和搜索框加入顶部容器
        topContainer.getChildren().addAll(dateControlBox, searchBox);
        root.setTop(topContainer);
        
        // 任务列表，任务列表绑定过滤后的数据
        todoListView = new ListView<>();
        todoListView.setPrefHeight(400);
        todoListView.setCellFactory(param -> new TodoCell());
        todoListView.setStyle("-fx-background-color: white; -fx-border-color: #cccccc; -fx-border-width: 5px;");
        root.setCenter(todoListView);
        
        // 底部输入和按钮区域
        HBox inputBox = createInputBox();
        root.setBottom(inputBox);
        
        // 加载当前日期的任务（首次启动时触发搜索初始化）
        loadTasksForCurrentDate();
        
        return new Scene(root, 600, 500);
    }
    
    // 日期控件区域
    private HBox createDateControlBox() {
        HBox dateBox = new HBox(10);
        dateBox.setPadding(new Insets(10));
        dateBox.setAlignment(Pos.CENTER);
        dateBox.setStyle("-fx-background-color: white; -fx-border-color: #cccccc; -fx-border-radius: 5px;");
        
        Button prevDayButton = new Button("<< 前一天");
        prevDayButton.setOnAction(e -> changeDate(-1));
        prevDayButton.setStyle("-fx-background-color: #2196F3; -fx-text-fill: white; -fx-padding: 5px 10px; -fx-background-radius: 8px; -fx-effect: dropshadow(gaussian, #888, 2, 0, 0, 1);");
        
        dateLabel = new Label(currentDate.format(dateFormatter));
        dateLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
        
        Button nextDayButton = new Button("后一天 >>");
        nextDayButton.setOnAction(e -> changeDate(1));
        nextDayButton.setStyle("-fx-background-color: #2196F3; -fx-text-fill: white; -fx-padding: 5px 10px; -fx-background-radius: 8px; -fx-effect: dropshadow(gaussian, #888, 2, 0, 0, 1);");
        
        Button pickDataButton = new Button("选择日期");
        pickDataButton.setOnAction(e -> {
            DatePicker datePicker = new DatePicker(currentDate);
            datePicker.setOnAction(event -> {
                LocalDate selectedDate = datePicker.getValue();
                if (selectedDate != null) {
                    currentDate = selectedDate;
                    dateLabel.setText(currentDate.format(dateFormatter));
                    loadTasksForCurrentDate(); // 切换日期后重新加载过滤数据
                }
            });
            // 弹出日期选择器
            Stage popupStage = new Stage();
            VBox vbox = new VBox(datePicker);
            vbox.setPadding(new Insets(30));
            Scene scene = new Scene(vbox);
            popupStage.setScene(scene);
            popupStage.setTitle("选择日期");
            popupStage.initOwner(pickDataButton.getScene().getWindow());
            popupStage.show();
        });
        pickDataButton.setStyle("-fx-background-color: #ff9800; -fx-text-fill: white; -fx-padding: 5px 10px; -fx-background-radius: 8px; -fx-effect: dropshadow(gaussian, #888, 2, 0, 0, 1);");
        
        dateBox.getChildren().addAll(prevDayButton, dateLabel, nextDayButton, pickDataButton);
        return dateBox;
    }
    
    // 搜索框区域
    private HBox createSearchBox() {
        HBox searchBox = new HBox();
        searchBox.setPadding(new Insets(5));
        searchBox.setStyle("-fx-background-color: white; -fx-border-color: #cccccc; -fx-border-radius: 5px;");
        
        // 获取 Search 控制器内部的 TextField（避免重复创建）
        TextField searchField = searchController.getSearchField();
        // 搜索框样式
        searchField.setPromptText("搜索待办事项...");
        searchField.setStyle("-fx-padding: 5px; -fx-font-size: 14px;");
        HBox.setHgrow(searchField, Priority.ALWAYS);    // 搜索框占满水平空间
        
        searchBox.getChildren().add(searchField);
        return searchBox;
    }
    
    // 底部输入区域
    private HBox createInputBox() {
        HBox inputBox = new HBox(10);
        inputBox.setPadding(new Insets(10));
        inputBox.setStyle("-fx-background-color: white; -fx-border-color: #cccccc; -fx-border-radius: 5px;");
        
        inputField = new TextField();
        inputField.setPromptText("输入新的待办事项...");
        inputField.setOnKeyPressed(e -> {
            if (e.getCode().toString().equals("ENTER")) {
                addTask();
            }
        });
        inputField.setStyle("-fx-padding: 5px; -fx-font-size: 14px;");
        
        // 优先级选择标签
        Label priorityLabel = new Label("");
        priorityComboBox.setPrefWidth(90);
        priorityComboBox.setPrefHeight(28);
        priorityComboBox.setStyle("-fx-background-color: #D3D3D3; -fx-font-size: 13px;");
        
        Button addButton = new Button("添加");
        addButton.setOnAction(e -> addTask());
        addButton.setPrefWidth(70);
        addButton.setPrefHeight(26);
        addButton.setStyle("-fx-background-color: #4CAF50; -fx-text-fill: white; -fx-padding: 5px 15px; -fx-background-radius: 8px; -fx-effect: dropshadow(gaussian, #888, 2, 0, 0, 1);");
        
        Button completeButton = new Button("完成");
        completeButton.setOnAction(e -> completeTask());
        completeButton.setPrefWidth(70);
        completeButton.setPrefHeight(26);
        completeButton.setStyle("-fx-background-color: #2196F3; -fx-text-fill: white; -fx-padding: 5px 15px; -fx-background-radius: 8px; -fx-effect: dropshadow(gaussian, #888, 2, 0, 0, 1);");
        
        Button deleteButton = new Button("删除");
        deleteButton.setOnAction(e -> deleteTask());
        deleteButton.setPrefWidth(70);
        deleteButton.setPrefHeight(26);
        deleteButton.setStyle("-fx-background-color: #f44336; -fx-text-fill: white; -fx-padding: 5px 15px; -fx-background-radius: 8px; -fx-effect: dropshadow(gaussian, #888, 2, 0, 0, 1);");
        
        HBox.setHgrow(inputField, Priority.ALWAYS);
        inputBox.getChildren().addAll(inputField, priorityLabel, priorityComboBox, addButton, completeButton, deleteButton);
        
        return inputBox;
    }
    
    // 加载任务时绑定搜索过滤
    private void loadTasksForCurrentDate() {
        // 1. 获取当前日期的原始任务列表（不经过滤）
        // 存储原始任务列表，用于搜索过滤
        ObservableList<TodoItem> originalItems = manager.getTodoItemsForDate(currentDate);
        // 2. 将原始列表传给搜索控制器，用于后续过滤
        searchController.setOriginalItems(originalItems);
        // 3. 关键：列表视图显示【过滤后的任务】（而非原始列表）
        todoListView.setItems(searchController.getFilteredItems());
    }
    
    // 切换日期
    private void changeDate(int daysToAdd) {
        currentDate = currentDate.plusDays(daysToAdd);
        dateLabel.setText(currentDate.format(dateFormatter));
        loadTasksForCurrentDate();          // 切换日期后重新加载过滤数据
    }
    
    // 添加任务
    private void addTask() {
        String text = inputField.getText().trim();
        if (!text.isEmpty()) {
            TodoItem.Priority selectedPriority = priorityComboBox.getValue();
            manager.addTodoItem(text, currentDate, selectedPriority);
            inputField.clear();
            loadTasksForCurrentDate();      // 添加后重新加载，确保搜索结果同步
        }
    }
    
    // 完成任务
    private void completeTask() {
        TodoItem selectedItem = todoListView.getSelectionModel().getSelectedItem();
        if (selectedItem != null) {
            manager.markItemAsCompleted(selectedItem);
            loadTasksForCurrentDate();      // 完成后重新加载，确保搜索结果同步
        }
    }
    
    // 删除任务
    private void deleteTask() {
        TodoItem selectedItem = todoListView.getSelectionModel().getSelectedItem();
        if (selectedItem != null) {
            manager.deleteItem(selectedItem);
            loadTasksForCurrentDate();      // 删除后重新加载，确保搜索结果同步
        }
    }
    
    // 自定义单元格渲染
    private static class TodoCell extends ListCell<TodoItem> {
        @Override
        protected void updateItem(TodoItem item, boolean empty) {
            super.updateItem(item, empty);
            if (empty || item == null) {
                setText(null);
                setStyle("");
            } else {
                setText(item.toString());
                if (item.isCompleted()) {
                    setTextFill(isSelected() ? Color.web("#555555") : Color.GRAY);
                    setStyle("-fx-font-style: italic;");
                } else {
                    // 根据优先级设置不同的文本颜色
                    switch (item.getPriority()) {
                        case HIGH:
                            setTextFill(Color.RED); break;
                        case MEDIUM:
                            setTextFill(Color.BLUE); break;
                        case LOW:
                            setTextFill(Color.BLACK); break;
                    }
                    setStyle("-fx-font-weight: bold;");
                }
                
                // 设置选中行背景色
                if (isSelected()) {
                    setStyle(getStyle() + "-fx-background-color: #B2EBF2;");
                }
            }
        }
    }
}